package com.guinea.account.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;

import com.guinea.account.entity.Resource;
import com.guinea.account.form.ResourceForm;
import com.guinea.account.service.ResourceManager;
import com.guinea.account.service.RoleManager;
import com.guinea.core.service.CRUDManager;
import com.guinea.core.web.StrutsEntityAction;

public class ResourceAction extends StrutsEntityAction {

	private RoleManager roleManager;

	private ResourceManager resourceManager;

	public CRUDManager getEntityManager() {
		return (CRUDManager) getResourceManager();
	}

	public ResourceManager getResourceManager() {
		return resourceManager;
	}

	public void setResourceManager(ResourceManager resourceManager) {
		this.resourceManager = resourceManager;
	}

	public RoleManager getRoleManager() {
		return roleManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}	

	/**
	 * 显示Form表单时的回调函数.为Form对象添加更多属性,在子类重载.
	 */
	public void onInitForm(ActionForm form, HttpServletRequest request,
			Object object) {
		if (id != null) {
			String[] relativeRoleIds = getResourceManager()
					.getRelativeRoleIds(id);
			ResourceForm resourceForm = (ResourceForm) form;
			resourceForm.setRelativeRoleIds(relativeRoleIds);
		}
	}

	/**
	 * 保存Form表单时的回调函数.为业务对象添加更多属性，在子类重载.
	 */
	public void onInitEntity(ActionForm form, HttpServletRequest request,
			Object object) {
		Resource resource = (Resource)object;
        String[] relativeRoleIds = request.getParameterValues("relativeRoleIds");
        resource.getRoles().clear();
        for (int i = 0; relativeRoleIds != null &&  i < relativeRoleIds.length; i++) {
            Long roleId = new Long(relativeRoleIds[i]);
            resource.getRoles().add(roleManager.get(roleId));
        }
	}
	public void doSaveEntity(HttpServletRequest request, Object object) {
		getResourceManager().saveResource((Resource)object);
	}

	public void doEraseEntity(HttpServletRequest request, Object object) {
		getResourceManager().eraseResource((Resource)object);
	}

	public void doDeleteEntity(HttpServletRequest request, Object object) {
		getResourceManager().deleteResource((Resource)object);
	}
}
